<template>
  <el-dialog title="智能控制" :visible.sync="visible" width="944px" append-to-body custom-class="fen_IntelligentControl">
    <el-form
      ref="queryform"
      :model="queryParams"
      label-width="0px"
      size="mini"
    >
      <el-form-item
        prop="locationId"
        :rules="[{ required: true, message: '请选择隧道', trigger: 'blur' }]"
        style="margin-bottom: 16px;width: 100%;"
      >
        <el-radio-group
          v-model="queryParams.locationId"
          size="small"
          @change="locationIdChange"
        >
          <el-radio-button
            v-for="tunnel in tunnelAll"
            :key="tunnel.id"
            :label="tunnel.id"
          >{{ tunnel.tunnelName }}（{{ tunnel.direction }}）</el-radio-button>
        </el-radio-group>
        <el-button v-hasPermi="['fen:intelligentControl:add']" style="float: right;" type="primary" @click="handleAdd">添加</el-button>
      </el-form-item>
    </el-form>
    <el-form ref="form" :model="form" :rules="rules" label-width="0px" size="mini">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" size="small" border="">
        <el-table-column prop="environmentalTarget" label="环境指标" align="center">
          <template slot-scope="scope">
            <el-form-item
              v-if="scope.$index === current"
              prop="environmentalTarget"
              :rules="[
                { required: true, message: '请选择环境指标', trigger: 'blur'},
              ]"
            >
              <el-select v-model="form.environmentalTarget" placeholder="请选择环境指标" size="mini">
                <el-option
                  v-for="dict in gasTypeDicts"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <span v-else>{{ gasTypeFormat(scope.row) }}({{ gasUnitFormat(scope.row) }})</span>
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="阙值" align="center">
          <template slot-scope="scope">
            <template v-if="scope.$index === current">
              <el-form-item
                prop="compareSize"
                :rules="[
                  { required: true, message: '请选择', trigger: 'blur'},
                ]"
                style="display: inline-block;"
              >
                <el-select v-model="form.compareSize" placeholder="请选择" size="mini" style="width: 55px;">
                  <el-option label=">" value="gt" />
                  <el-option label="<" value="lt" />
                  <el-option label="≥" value="gt=" />
                  <el-option label="<=" value="lt=" />
                </el-select>
              </el-form-item>
              <el-form-item
                prop="threshold"
                :rules="[
                  { required: true, message: '请输入阙值', trigger: 'blur'},
                ]"
                label-width="0"
                style="display: inline-block;padding: 0;margin:0;"
              >
                <el-input v-model="form.threshold" style="width:80px;margin-left: 10px;" size="mini" />
              </el-form-item>
            </template>
            <span v-else>{{ thresholdFormat(scope.row) }}
              <!-- {{ scope.row.compareSize }} {{ scope.row.threshold }}({{ gasUnitFormat(scope.row) }}) -->
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="equId" label="控制设备" align="center">
          <template slot-scope="scope">
            <template v-if="scope.$index === current">
              <el-form-item
                prop="equId"
                :rules="[
                  { required: true, message: '请输入阙值', trigger: 'blur'},
                ]"
              >
                <el-select
                  v-model="form.equId"
                  placeholder="请选择设备"
                  size="mini"
                  multiple
                  filterable
                  @change="equChange(scope.row)"
                >
                  <el-option
                    v-for="equ in euqList"
                    :key="equ.equName"
                    :label="equ.equName"
                    :value="equ.id+''"
                  />
                </el-select>
              </el-form-item>
            </template>
            <span v-else>{{ scope.row.equName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="运行频率" align="center">
          <template slot-scope="scope">
            <el-form-item
              v-if="scope.$index === current"
              prop="level"
              :rules="[
                { required: true, message: '请输入运行频率', trigger: 'blur'},
                { validator: validateLevel, trigger: 'blur' }
              ]"
            >
              <el-input v-model="form.level" type="number" :min="0" :max="50" style="width:80px;margin-left: 10px;" size="mini" />Hz
            </el-form-item>
            <span v-else>{{ scope.row.level }}Hz</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运行状态" align="center" width="82px;">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 1" class="text-info">运行</span>
            <span v-if="scope.row.status === 0 || scope.row.status === '0' ">停止</span>
          </template>
        </el-table-column>
        <el-table-column v-hasPermi="['fen:intelligentControl:edit']" prop="address" label="操作" align="center" width="120px">
          <template slot-scope="scope">
            <!--  -->
            <template v-if="scope.$index === current">
              <el-button type="text" size="mini" @click="submitForm">提交</el-button>
              <el-divider direction="vertical" />
              <el-button type="text" size="mini" @click="current = null">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="handEdit(scope.$index,scope.row)">编辑</el-button>
              <el-divider direction="vertical" />
              <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <!-- <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="submitForm">提交</el-button>
      <el-button size="small" @click="cancel">取 消</el-button>
    </div> -->
  </el-dialog>
</template>

<script>
import { queryEqu } from '@/api/fjgs/equ'
import { listAll } from '@/api/system/tunnel'
import { listControl, getControl, delControl, addControl, updateControl } from '@/api/fjgs/fjIntelligentControl'
import { cloneDeep } from 'loadsh'
export default {
  data() {
    // const validateLevel = (rule, value, callback) => {
    //   console.log(value)
    //   if (value > 50 || value < 0) {
    //     callback(new Error('请输入0~50的有效数值'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      visible: false,
      loading: false,
      current: '',
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        locationId: ''
      },
      oldLocationId: undefined,
      tableData: [],
      form: {
        environmentalTarget: '',
        compareSize: '',
        threshold: '',
        equId: [],
        level: ''
      },
      rules: {
        // environmentalTarget: [{ required: true, message: '请选择环境指标', trigger: 'blur' }],
        // compareSize: [{ required: true, message: '请选择', trigger: 'blur' }],
        // threshold: [{ required: true, message: '请输入阙值', trigger: 'blur' }],
        // equId: [{ required: true, message: '请输入阙值', trigger: 'blur' }],
        // level: [{ validate: validateLevel, trigger: 'blur' }]
      },
      gasTypeDicts: [],
      gasTypeUnitDicts: [],
      tunnelAll: [],
      euqList: [],
      operatorDicts: [
        { label: '>', value: 'gt' },
        { label: '<', value: 'lt' },
        { label: '>=', value: 'gt=' },
        { label: '<=', value: 'lt=' }
      ]
    }
  },
  created() {
    this.getDicts('gas_type').then(response => {
      this.gasTypeDicts = response.data
    })
    this.getDicts('gas_type_unit').then(response => {
      this.gasTypeUnitDicts = response.data
    })
    listAll().then(res => {
      this.tunnelAll = res.data
    })
  },
  methods: {
    // 气体单位
    gasTypeFormat(row, column) {
      return this.selectDictLabel(this.gasTypeDicts, row.environmentalTarget)
    },
    gasUnitFormat(row, column) {
      const item = this.gasTypeUnitDicts.find(e => e.dictLabel === row.environmentalTarget)
      return item ? item.dictValue : ''
    },
    thresholdFormat(row) {
      // compareSize
      const operatorItem = this.operatorDicts.find(e => e.value == row.compareSize)
      let operator = ''
      if (operatorItem) {
        operator = operatorItem.label
      }
      const unit = this.gasUnitFormat(row)
      return operator + ' ' + row.threshold + unit
      // row.compareSize
    },
    locationIdChange(v) {
      if (typeof this.current === 'number') {
        this.msgError('请先提交/取消编辑行的操作')
        setTimeout(() => {
          this.queryParams.locationId = this.oldLocationId
        }, 100)
      } else {
        this.euqList = []
        this.tableData = []
        this.getList()
        this.oldLocationId = v
        queryEqu({
          locationId: this.queryParams.locationId,
          equType: 1
        }).then(res => {
          this.euqList = res.data
        })
      }
    },
    equChange(row) {
      if (Array.isArray(this.form.equId)) {
        const equNames = []
        this.euqList.map(e => {
          if (this.form.equId.includes(String(e.id))) {
            equNames.push(e.equName)
          }
        })
        this.form.equName = equNames.join(',')
      }
    },
    open(options) {
      this.visible = true
    },
    handleAdd() {
      this.$refs.queryform.validate((valid) => {
        if (valid) {
          this.tableData.push({ environmentalTarget: '',
            compareSize: '',
            threshold: '',
            equId: '',
            level: '' })
        }
      })
    },
    handEdit(index, row) {
      if (typeof this.current === 'number') {
        this.msgError('请先提交/取消编辑行的操作！')
      } else {
        this.current = index
        const r = cloneDeep(row)
        r.equId = r.equId ? r.equId.split(',') : []
        this.form = r
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (typeof this.current === 'number') {
        this.msgError('请先提交/取消编辑行的操作！')
        return
      }
      const ids = row.id
      if (ids) {
        this.$confirm('是否确认删除环境指标为"' + this.gasTypeFormat(row) + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delControl(ids)
        }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        }).catch(() => {})
      } else {
        const idx = this.tableData.findIndex(e => e === row)
        this.tableData.splice(idx, 1)
      }
    },
    /** 查询职能控制列表 */
    getList() {
      this.loading = true
      listControl(this.queryParams).then(response => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    validateLevel(rule, value, callback) {
      console.log(value)
      if (value > 50 || value < 0) {
        callback(new Error('请输入0~50的有效数值'))
      } else {
        callback()
      }
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const params = {
            locationId: this.queryParams.locationId,
            ...this.form,
            equId: this.form.equId.join(',')
          }
          if (this.form.id != null) {
            updateControl(params).then(response => {
              this.msgSuccess('修改成功')
              this.current = null
              this.getList()
            })
          } else {
            addControl(params).then(response => {
              this.msgSuccess('新增成功')
              this.current = null
              this.getList()
            })
          }
        }
      })
    },
    // submitForm() {

    // },
    cancel() {

    }
  }
}
</script>

<style lang="scss" >
.fen_IntelligentControl {
    .el-dialog__body {
      padding: 16px 20px;
    }
    .el-table .el-input__inner{
      padding-left: 10px !important;
    }
}

</style>
